// 全局变量
var caselistDt='';
var caseDialog=''; //病历弹窗变量
var patientSel='';
var orderDialog='';

var DocData={
    userInfo:{
        userName:'',
        userId:baseFn.getQueryString('userId',true)
    },
    patientInfo:{
        patientId:baseFn.getQueryString('patientId',true),
    },
    bookingInfo:{
        bookingId:baseFn.getQueryString('bookingId',true),
        subclinicId:baseFn.getQueryString('subclinicId',true),
        userPhone:'',
        userPhones:'',
        canSave:false,
        canSelGoods:baseFn.notNull(baseFn.getQueryString('bookingId'))?true:false,
        treatmentOk:true
    },
    sendbooking:false,
    cashierId:SessionData.userId,//后台登陆用户
    orderId:baseFn.getQueryString('orderId',true),
    userId:baseFn.getQueryString('userId',true),
    userName:'',
    patientId:baseFn.getQueryString('patientId',true),
    doctorId:SessionData.userId,
    subclinicId:SessionData.subclinicId,
    pay:0,
    cost:0,
    payService:0,
    payGoods:0,
    userCardList:[],
    goodsList:[],
    serviceList:[],
    goodsIds:[],//选中商品列表
    serviceIds:[],//选中服务列表，
    newMainList:[],//主症数据
    newDiseaseList:[],//兼症数据
    point:[],//配穴数据
    clusion:false,//诊断结论是否加载完毕
    imgChange: false,
    orderData:'',
    payWay:0,//付款方式(服务付款方式) 0:余额;1:支付宝;2:微信;3:现金;4:Pos机;5:次卡
    payWays:0,//付款方式(商品付款方式)
    payUserId:'',//代付人id
    otherPay:false,//是否启用代付
    otherCanPay:true,//启用了代付之后是否可以付款
    couponId:'',
    couponMoney:0,
    couponList:[],
    orderURL:'/xrtn-manager/order/gotoOrder',
    canPay:false,//订单是否改变
    pCanUpBooking:false,

    // add by TreeJohn
    // 特病相关
    totalSpecialScore:0,
    checkResult:0,
    realResult:0,
    error:0,
    bookingStatus:baseFn.getQueryString('bookingStatus',-1),
    treatmentState:baseFn.getQueryString('treatmentState',-1),

    renderPatientInfo:function(data,canEdit){//渲染宝宝基本信息数据
        var _data=data,that=this,_canEdit=canEdit || false;
        if(typeof _data == 'boolean'){
            if(_data){

            }else{

            }
        }
        $('.Baby_Healthy_home_billing_right_center').eq(1).removeClass('hidden').siblings(".Baby_Healthy_home_billing_right_center").addClass("hidden");//最外层窗口显示
        $('#firstId').addClass("bgc_alert").siblings().removeClass("bgc_alert");//第一侧边栏显示
        var _pDom = $('.billing_right_center_details')
        if(_canEdit){
            _pDom.find('input').removeClass('borderNone').prop("readonly",false);
            _pDom.find('textarea').removeClass('borderNone').prop("readonly",false);
            _pDom.find('select').removeClass('borderNone').addClass('select_arrow').attr("disabled",false);
            _pDom.find('.billing_right_tipBtn').removeClass('hidden');
            _pDom.find('.billing_keep').show();
            $('.illHistory').hide();
            _pDom.find('input[type=file]').prop("readonly",false).prop("disabled",false);
        }else{
            _pDom.find('input').addClass('borderNone').prop("readonly", true);
            _pDom.find('textarea').addClass('borderNone').prop("readonly", true);
            _pDom.find('select').addClass('borderNone').removeClass('select_arrow').attr("disabled", true);
            _pDom.find('.billing_right_tipBtn').addClass('hidden');
            _pDom.find('.billing_keep').hide();
            $('.editorInfo').attr('rel','off').text("编辑");
            $('.illHistory').show();
            _pDom.find('input[type=file]').prop("readonly",true).prop("disabled",true);
        }
    },
    canRenderCase:function(){
        if(this.newMainList.length != 0 && this.newDiseaseList.length != 0 && this.point.length != 0 && this.clusion){
            return true
        }else{
            return false
        }
    },//是否渲染病历
    canRenderOrderList:function(){//判断能否渲染订单并渲染订单列表
        if(this.serviceList.length != 0 && $('.js_project_wrap').length == 2 && this.orderData !== '' && baseFn.notNull(this.userCardList)){
            $('.js_project_wrap').find('.tuinaList').remove()
            var _data = this.orderData;
            for(var i=0;i<_data.serviceList.length;i++){
                //$('#tuinaList').find('input[value='+_data.serviceList[i].serviceId+']').trigger('click')
                var _serviceData={
                    value:_data.serviceList[i].serviceId,//服务id或者商品id
                    cardId:_data.serviceList[i].cardId,//卡id
                    name:_data.serviceList[i].serviceName,
                    cost:_data.serviceList[i].serviceCost,
                    num:_data.serviceList[i].cardNumber,
                    useCard:_data.serviceList[i].isUse
                }
                var _outData = DocData.arrFilter(this.userCardList,'cardId',_serviceData.cardId,'','out')
                if(!_outData){
                    var _newData = DocData.arrFilter(this.userCardList,'serviceId',_serviceData.value,'','out')
                    if(_newData){
                        _serviceData.cardId = _newData[0].cardId
                        _serviceData.num = 1
                    }else{
                        _serviceData.cardId = ''
                        _serviceData.num = 0
                        _serviceData.useCard = 0
                    }
                }
                this.renderGoodsCar('service',_serviceData)
                $('#tuinaList').find('input[value='+_data.serviceList[i].serviceId+']').addClass('checkBox_checked')
            }
            for(var j=0;j<_data.goodsList.length;j++){
                var _goodSData={
                    value:_data.goodsList[j].goodsId,//服务id或者商品id
                    name:_data.goodsList[j].goodsName,
                    cost:_data.goodsList[j].goodsCost,
                    num:_data.goodsList[j].orderNum
                }
                DocData.renderGoodsCar('goods',_goodSData)

            }
            sumLit()
            // if(baseFn.notNull(DocData.orderHaveChange)){
            //     baseFn.infoDialog('该订单中所选服务的计次卡使用情况出现更改')

            // }
        }else{
            return false
        }
    },
    initOrder:function(data){//收款确认单
        var that=this,_data = data || (this.orderData == ''?{}:this.orderData);
        var _opts={
            payUserId:baseFn.notNull(_data.orderInfo.payUserId)?_data.orderInfo.payUserId:'',
            payUserName:baseFn.notNull(_data.orderInfo.payUserName)?_data.orderInfo.payUserName:'',
            payUserPhone:baseFn.notNull(_data.orderInfo.payUserPhone)?_data.orderInfo.payUserPhone.substring(0,3)+'****'+_data.orderInfo.payUserPhone.substring(7):'',
            orderNo:_data.orderInfo.orderNo,
            createTimetr:baseFn.notNull(_data.orderInfo.createTime)?baseFn.timestampToTime(_data.orderInfo.createTime):'',
            userName:_data.userInfo.userName,
            userPhone:baseFn.notNull(_data.userInfo.userPhone)?_data.userInfo.userPhone.substring(0,3)+'****'+_data.userInfo.userPhone.substring(7):'',
            cashierName:baseFn.notNull(_data.orderInfo.cashierName)?_data.orderInfo.cashierName:'',
            serviceList:_data.serviceList,
            goodsList:_data.goodsList,
            couponId:baseFn.notNull(_data.orderInfo.couponId)?_data.orderInfo.couponId:'',
            pay:_data.orderInfo.orderPayCost,
            payTotal:_data.orderInfo.orderTotalCost,
            couponInfo:baseFn.notNull(_data.cardInfo)?_data.cardInfo:'',
            userAccount:that.userInfo.userAccount
        }
        // console.log(_opts)
        var _pDom = $('.gatheringlist')
        _pDom.find('.js_orderNo').text(_opts.orderNo)
        _pDom.find('.js_createTimetr').text(_opts.createTimetr)
        _pDom.find('.js_userName').text(_opts.userName)
        _pDom.find('.js_userPhone').text(_opts.userPhone)
        _pDom.find('.js_userAccount').text('￥ ' + _opts.userAccount)
        _pDom.find('.js_outTime').text(baseFn.timestampToTime(DocData.userInfo.outTime))
        _pDom.find('.js_cashierName').text(_opts.cashierName)
        _pDom.find('.detaillist .serviceelm').remove();
        _pDom.find('.detaillist .goodselm').remove();
        _pDom.find('.zccardelm .payelm').removeClass('active')
        _pDom.find('.zccardelm .payelm[rel=0]').addClass('active')
        if(_opts.serviceList && _opts.serviceList.length != 0){
            _pDom.find('.js_paywrap_service').removeClass('hidden')
            that.payWay=0
        }else{
            _pDom.find('.js_paywrap_service').addClass('hidden');
            that.payWay=''
        }
        if(_opts.goodsList && _opts.goodsList.length != 0){
            _pDom.find('.js_paywrap_goods').removeClass('hidden')
            that.payWays=0
        }else{
            _pDom.find('.js_paywrap_goods').addClass('hidden'),
                that.payWays=''
        }
        //他人代付
        if(DocData.otherPay){
            _pDom.find('.js_paywrap_goods').addClass('hidden')
            _pDom.find('.js_paywrap_service').addClass('hidden')
            _pDom.find('.js_paywrap_other').removeClass('hidden')

        }else{
            _pDom.find('.js_paywrap_other').addClass('hidden')
        }

        for(var i=0;i<_opts.serviceList.length;i++){
            var _elm = _opts.serviceList[i]
            var _html = '<div class="row serviceelm">\
                            <div class="col-sm-6"><p>'+_elm.serviceName+'</p><p class="'
            if(_elm.isUse == 0){
                _html += 'hidden'
            }
            _html += '">使用计次卡</p></div>\
                            <div class="col-sm-4">\
                                <p class="font_right">x<span class="num">1</span></p>\
                            </div>\
                            <div class="col-sm-2 font_right">\
                                <p class="money font_right">￥<span>'+_elm.serviceCost+'</span></p>\
                                <p class="'
            if(_elm.isUse == 0){
                _html += 'hidden'
            }
            _html += ' font_right">-<span>'+_elm.serviceCost+'</span></p>\
                            </div>\
                        </div>'
            _pDom.find('.couponwrap').before(_html)
        }

        for(var j=0;j<_opts.goodsList.length;j++){
            var _elm = _opts.goodsList[j]
            var _html2 = '<div class="row goodselm">\
                            <div class="col-sm-6">'+_elm.goodsName+'</div>\
                            <div class="col-sm-4">\
                                <p class="font_right">x<span class="num">'+_elm.orderNum+'</span></p>\
                            </div>\
                            <div class="col-sm-2 font_right">\
                                <p class="money font_right">￥<span>'+_elm.goodsCost+'</span></p>\
                            </div>\
                        </div>'
            _pDom.find('.couponwrap').before(_html2)
        }

        if(_opts.couponId !=''){
            $('.couponwrap').find('.couponName').text(_opts.couponInfo.cardName)
            if(_opts.couponInfo.cardType == 1 || _opts.couponInfo.cardType == 3){
                $('.couponwrap').find('.couponMoney').text(_opts.couponInfo.discountCosts)
                //满减
            }else if(_opts.couponInfo.cardType == 2){
                //体验券
                if(baseFn.notNull(_opts.couponInfo.serviceName)){
                    $('.couponwrap').find('.couponMoney').text(_opts.couponInfo.serviceName+'1次')
                }else{
                    $('.couponwrap').find('.couponMoney').text('使用了“'+_opts.couponInfo.cardName+'”体验券')
                }

            }
            // $('.couponwrap').find('.couponMoney').text('0')
        }else{
            $('.couponwrap').find('.js_couponName').text('')
            $('.couponwrap').find('.couponMoney').text('未使用优惠券')
        }
        _pDom.find('.littlesumwrap').find('.littlesum span').data('cost',_opts.pay).text('￥ '+_opts.pay)
        _pDom.find('.countsum').data('cost',_opts.payTotal).find('span').text('￥ '+_opts.pay)

    },
    renderGoodsCar:function(type,data){
        //右侧购物车订单列表
        var _data = data
        if(type == 'service'){
            var html='<div class="tuinaList">\
                            <div class="row newAddBtn" style="font-size: 15px;" rel="'+_data.value+'" data-cost="'+_data.cost+'" data-cardid="'+_data.cardId+'">\
                                <div class="col-sm-8 patientDesc font_left texthidden">'+_data.name+'</div>\
                                <div class="col-sm-4 font_right"><span>￥'+_data.cost+'</span><i style="margin-left: 1rem" class="icon iconfont icon-shanchu deleteFr"></i></div>\
                            </div>'
            if(_data.num != 0){
                html +='<div class="bg_e4 card_wrap">\
                            <div class="row">\
                                <div class="col-sm-8 font_left">\
                                    <span class="patientDesc" style="padding-left: 10px">可使用计次卡</span>\
                                </div>\
                                <div class="col-sm-4 font_right">\
                                    <select class="js_serviceSelCard bg_e4" style="padding-right: 10px;outline: none" value="">\
                                    <option value="0" '+(_data.useCard==0 && 'selected')+'>本次不使用计次卡</option>\
                                    <option value="1" '+(_data.useCard==1 && 'selected')+'>本次使用计次卡</option>\
                                    </select>\
                                </div>\
                            </div>\
                            </div>';
            }
            html +='</div>'
            var $html=$(html)
            if(_data.useCard==1){
                $html.find('.newAddBtn').addClass('cardoff')
            }
            $('#js_serviceBox').append($html);
        }else if(type == 'goods'){
            var html2 ='<div class="tuinaList">\
                    <div class="newAddBtn" rel="'+_data.value+'" data-cost="'+_data.cost+'">\
                    <div class="fl" style="max-width:54%">\
                    <span class="patientDesc texthidden" style="width:100%;display:block">'+_data.name+'</span>\
                    </div>\
                    <div class="fr">\
                        <div  class="" style="display: inline-block;margin-right: 1rem;line-height: 0.8rem">\
                            <span class="addNum" rel="0"><i class="icon iconfont icon-jianhao"></i></span><span class="jishuNum">'+_data.num+'</span><span class="addNum" rel="1"><i class="icon iconfont icon-jiahao1"></i></span>\
                        </div>\
                        <span>￥</span>\
                        <span class="moneyNumberTip">'+(_data.cost*100*_data.num/100)+'</span><i class="milk hidden">'+_data.cost+'</i>\
                        <span class="deleteFr"><i style="margin-left: 1rem" class="icon iconfont icon-shanchu"></i></span>\
                    </div>\
                </div>';
            $('#addProductBox_list').append(html2);
        }
    },
    saveOrder:function(goPay,btnDom){
        var _saveUrl=baseUrl.base+baseUrl.order;
        var _upData={
            userName:DocData.userInfo.userName,
            userId:DocData.userInfo.userId,
            bookingId:DocData.bookingInfo.bookingId,
            doctorId: DocData.doctorId,
            subclinicId:DocData.subclinicId,
            patientId:DocData.patientInfo.patientId,
            orderTotalCost:DocData.cost,
            orderPayCost:(DocData.pay-DocData.couponMoney)<0?0:(DocData.pay-DocData.couponMoney),
            couponId:DocData.couponId,//优惠券
            cardId:[],//卡
            goodsList:[],
            serviceList:[]
        }
        if(DocData.orderId != ''){
            _saveUrl += 'updateOrderInfo',
                _upData.orderId = DocData.orderId
            if(baseFn.notNull(DocData.payUserId)){
                _upData.payUserId=DocData.payUserId
            }
        }else{
            _saveUrl += 'saveOrderInfo'
        }

        for(var i=0;i<DocData.serviceIds.length;i++){
            var _ids= DocData.serviceIds[i]
            var _temp = DocData.serviceList.filter(function(val){
                return val.serviceId == _ids
            })
            if(_temp && _temp.length != 0){
                _upData.serviceList.push(_temp[0])
            }
        }
        if(_upData.serviceList.length == 0){
            baseFn.infoDialog('请至少选择一项推拿服务！')
            if(orderDialog != ''){
                orderDialog.close();
                orderDialog = ''
            }
            if(btnDom){
                $(btnDom).attr('rel',0)
            }

            return false
        }
        for(var j=0;j<DocData.goodsIds.length;j++){
            var _ids= DocData.goodsIds[j]
            var _num = Number($('.js_project_wrap[rel=2]').find('.newAddBtn[rel='+_ids+']').find('span.jishuNum').text())
            var _temp = DocData.goodsList.filter(function(val){
                return val.goodsId == _ids
            })
            if(_temp.length != 0){
                _temp[0].orderNum = _num
                _upData.goodsList.push(_temp[0])
            }
        }
        $('.card_wrap').each(function(k,m){
            if($(m).find('.js_serviceSelCard').val() == 1){
                _upData.cardId.push($(m).siblings('.newAddBtn').data('cardid'))
            }

        })
        _upData.cardId=_upData.cardId.join(',')
        //return false
        _upData.serviceList = JSON.stringify(_upData.serviceList);
        _upData.goodsList = JSON.stringify(_upData.goodsList);
        $.post(_saveUrl,_upData,function(res){
            if(res.code == 0){
                if(res.results && baseFn.notNull(res.results)){
                    DocData.orderId = res.results
                    $('.otherpay_wrap').removeClass('hidden')
                    if(baseFn.notNull(DocData.orderId)){
                        $('textarea.js_bookingDesc').prop('disabled',true)
                        $('#illSelectRight').prop('disabled',true)
                        $('#addIllPeople').addClass('hidden')
                    }
                }
                DocData.canPay=true

                if(goPay){
                    if(btnDom){
                        $(btnDom).attr('rel',0)
                    }
                    $('.consumeListContains .gatheringBtn').trigger('click')
                }else{
                    if(btnDom){
                        $(btnDom).attr('rel',0)
                    }
                    baseFn.infoDialog('保存成功！')
                }
            }else{
                if(btnDom){
                    $(btnDom).attr('rel',0)
                }
                baseFn.infoDialog(res.msg)
            }
        },'json').complete(function(){
            if(btnDom){
                $(btnDom).attr('rel',0)
            }
        })
    },
    upBookingInfo:function(){
        var that = this
        var _upData={
            isAdd:that.bookingInfo.isAdd,
            bookingType:that.bookingInfo.bookingType,
            userId:that.userInfo.userId,
            patientId:that.patientInfo.patientId,
            bookingDesc:that.bookingInfo.bookingDesc,
            subclinicId:that.bookingInfo.subclinicId,
            doctorId:that.bookingInfo.doctorId
        }
        that.bookingInfo.patientId = that.patientInfo.patientId
        // if(that.notNull(that.bookingInfo.treatmentId)){
        //     _upData.treatmentId = that.bookingInfo.treatmentIds
        // }
        if(baseFn.notNull(that.bookingInfo.bookingId)){
            _upData.bookingId =  that.bookingInfo.bookingId
        }else{
            if(that.sendbooking){
                baseFn.infoDialog('预约正在提交中，不要重复操作')
                return false
            }
            that.sendbooking = true
        }
        baseFn.$post({
            url:'booking/saveBookingInfo',
            data:_upData,
            calFn:function(res){
                $('.js_saveBooking').attr('rel',0)
                if(baseFn.notNull(res.bookingId)){
                    that.bookingInfo.bookingId = res.bookingId
                }
                if(baseFn.notNull(res.treatmentId)){
                    that.bookingInfo.treatmentId = res.treatmentId
                }
                $('.js_saveBooking_wrap').addClass('hidden')
                that.bookingInfo.canSave=true;
                that.sendbooking = false
                if(baseFn.notNull(that.bookingInfo.bookingId) && baseFn.notNull(that.bookingInfo.treatmentId)){
                    //是否可以服务和商品
                    that.bookingInfo.canSelGoods = true
                }else{
                    that.bookingInfo.canSelGoods = false
                }
            },
            comFn:function(){
                that.sendbooking = false
            }
        })
    },
    caseListDLFn:function(){//历史病历列表弹窗
        if(caselistDt == ''){
            caselistDt = baseFn.rpDataTables('.js_caselist',{
                ajUrl:baseUrl.base+baseUrl.patient+'selectHistoryTreatmentList',
                ajDataSrc:"results",
                select:true,
                ajType:'get',
                ajData:{
                    patientId:DocData.patientInfo.patientId
                },
                autoWidth:false,
                select:false,
                scrollY:'50%',
                columns:[
                    {"data":"treatmentTime",width:"10%",defaultContent:'无',render:function(data,type,row, meta){
                            return baseFn.timestampToTime(data)
                        }},
                    {"data":"userName",width:"10%",defaultContent:'无'},
                    {"data": "diseaseInfo",width:"10%",defaultContent:'无',className:''},
                    {"data": "treatmentId",width:"10%",defaultContent:'',className:'',render:function(data,type,row, meta){
                            return '<a class="datatablebtn treatdetails" href="javascript:void(0)" data-vals="'+ data+'">查看详情</a>'
                        }}

                ],
                initComplete:function(){

                },
                drawCallback: function( settings ) {
                    var api = this.api();
                    var rows = api.rows({
                        page: 'current'
                    }).nodes();
                    for(var r1=0;r1<rows.length;r1++){
                        var _time = baseFn.timestampToTime(rows.data()[r1].treatmentTime)
                        $(rows).eq(r1).before('<tr class="caselist_tr"><td colspan="4">就诊时间：' + _time+'</td></tr>')
                    }
                    $('.treatdetails').off('click').on('click',function(){
                        var _treatId = $(this).data('vals')
                        getBabyListIllHandle(_treatId,true);
                        caseDialog.close()
                    })
                }
            })
        }else{
            caselistDt.settings()[0].ajax.data={
                patientId:DocData.patientInfo.patientId
            }
            caselistDt.ajax.reload()
        }
    },
    renderPatientSelList:function(){//宝宝就诊记录list
        var that= this
        if(!baseFn.notNull(patientSel)){
            patientSel = baseFn.rpDataTables('.patientsellist', {//就诊信息
                ajUrl: baseUrl.base + baseUrl.patient + 'selectPatientList',
                ajDataSrc: "results",
                ajData: {
                    patientId: that.patientInfo.patientId
                },
                scrollY:300,
                autoWidth: false,
                select: false,
                columns: [
                    {"data": "orderTime", width: "15%", defaultContent: ''},
                    {"data": "doctorName", width: "10%", defaultContent: ''},
                    {"data": "subclinicName", width: "10%", defaultContent: ''},
                    {"data": "bookingType",defaultContent:'无',width: '10%',render:function(data,type,row, meta){
                            if(data == 0){
                                return '调理身体'
                            }else{
                                return '预防保健'
                            }
                        }},
                    {"data": "isAdd",defaultContent:'无',width: '10%',render:function(data,type,row,meta){
                            if(data == 1 && row.bookingType == 0){
                                return '新治疗'
                            }else if(data == 1 && row.bookingType == 1){
                                return '--'
                            }else{
                                return '继续上次治疗'
                            }
                        }}
                ],
                initComplete: function () {},
                drawCallback: function (settings) {}
            })
        }else{
            patientSel.settings()[0].ajax.data = {patientId:that.patientInfo.patientId};
            patientSel.ajax.reload();
        }
    },
    arrFilter:function(data,keyName,keyVal,changeVal,type){
        var _data= data
        var _tempArrs =_data.filter(function(val){
            return  val[keyName] == keyVal
        });
        if(_tempArrs.length != 0){
            if(type != 'out'){
                var _tempArr = _tempArrs[0]
                if(type == 'all'){
                    _tempArr = _tempArrs
                }
                for(var i=0;i<_tempArr.length;i++){
                    _tempArr[i][keyName] = changeVal
                }
            }else{
                return _tempArrs
            }

        }else{
            return false
        }

    }
}

// ---------------- DocData 初始化结束 --------------------------

var baseHtml={
    home_billing_patientInfo:function(data){
        var _data = $.extend({},{
            patientImg:'',
            userId:'',
            patientId:'',
            bookingId:'',
            doctorId:'',
            subclinicId:'',
            patientName:'',
            patientBirthday:'',
            patientGender:'',
            patientHeight:'',
            patientAddress:'',
            patientBodyWeight:'',
            userSource:''
        },data || {});
        var _html = '<div class="editorInfo_box">\
                        <h4 class="billing_right_center_h4">基本档案</h4>\
                        <div class="editorInfo" rel="off">编辑</div>\
                    </div>\
                    <div class="billing_right_center_img">\
                        <span>头像</span>\
                        <div class="cols10">\
                            <form class="Js_uploadForm" method="post" enctype="multipart/form-data" id="Js_uploadForm" style= "height: 5rem;">\
                                <div class="Js_preview" style= "height: 5rem;">\
                                    <img class="imghead" border="0" src="'+_data.patientImg+'" width="70" height="60" onclick="changeImg()">\
                                </div>\
                                <input type="file" name="img" onchange="zcuploadImageCover(this)" style="display: none;" id="Js_previewImgNew" disabled>\
                            </form>\
                        </div>\
                    </div>\
                    <form id="baseForm" method="post" action="##" enctype="multipart/form-data">\
                        <div class="billing_right_center_details_box">\
                            <p>\
                                <input type="hidden" name="userId" value="'+_data.userId+'"/>\
                                <input type="hidden" name="patientId" value="'+_data.patientId+'"/>\
                                <input type="hidden" name="bookingId" value="'+_data.bookingId+'" />\
                                <input type="hidden" name="userImg" value="'+_data.patientImg+'" />\
                                <input type="hidden" name="doctorId" value="'+_data.doctorId+'"/>\
                                <input type="hidden" name="subclinicId" value="'+_data.subclinicId+'"/>\
                                <span>姓名</span>\
                                <input class="billing_right_center_details_input borderNone" type="text" name="userName" placeholder="请输入宝宝姓名" readonly="" value="'+_data.patientName+'">\
                            </p>\
                            <p>\
                                <span>生日</span>\
                                <input class="billing_right_center_details_input details_select borderNone" type="text" id="birthDay" name="userBirthday" placeholder="年/月/日" readonly="" value="'+_data.patientBirthday+'">\
                            </p>\
                            <p>\
                                <span>性别</span>\
                                <select id="details_select_opt" class="billing_right_center_details_input  details_select borderNone" name="patientGender" style="width: 19rem;" value="'+_data.patientGender+'">'
                                if(_data.patientGender == 1){
                                    _html += '<option value="1" selected>女</option><option value="0">男</option>'
                                }else{
                                    _html += '<option value="1">女</option><option value="0" selected>男</option>'
                                }
                                _html += '</select>\
                            </p>\
                            <p>\
                                <span>身高</span>\
                                <input class="billing_right_center_details_input details_select borderNone" name="userHeight" placeholder="cm" readonly="" value="'+_data.patientHeight+'">\
                            </p>\
                            <p>\
                                <span>地址</span>\
                                <input class="billing_right_center_details_input borderNone" type="text" name="userAddress" placeholder="请输入地址" readonly="" value="'+_data.patientAddress+'">\
                            </p>\
                            <p>\
                                <span>体重</span>\
                                <input class="billing_right_center_details_input details_select borderNone" name="userBodyWeight" placeholder="kg" readonly="" value="'+_data.patientBodyWeight+'">\
                            </p>\
                            <!--<p>\
                                <span>来源</span>\
                                <input class="billing_right_center_details_input borderNone" type="text" name="userSource" placeholder="请输入来源" readonly="" value="'+_data.userSource+'">\
                            </p>-->\
                        </div>\
                        <h4 class="billing_right_center_h4" style="margin-top: 3rem">既往病史档案</h4>\
                        <div id="caseOfIlliness" class="billing_right_center_details_box" style="padding-left:0.5rem">\
                            <div class="billing_right_tit">\
                                <span class="billing_right_tit_fontSize">*过敏史</span>\
                                <textarea class="billing_right_tit_textarea borderNone" name="allergyHistory" placeholder="请输入宝宝过敏史" readonly></textarea>\
                            </div>\
                            <div class="billing_right_tit hidden">\
                                <span class="billing_right_tit_fontSize">*个人病史</span>\
                                <textarea class="billing_right_tit_textarea borderNone" name="userHistory" placeholder="请输入宝宝个人病史" readonly></textarea>\
                            </div>\
                            <div class="billing_right_tit hidden">\
                                <span class="billing_right_tit_fontSize">*高烧惊厥史</span>\
                                <textarea class="billing_right_tit_textarea borderNone" name="feverHistory" placeholder="请输入宝宝高烧惊厥史" readonly></textarea>\
                            </div>\
                            <div class="billing_right_tit hidden">\
                                <span class="billing_right_tit_fontSize">*用药史</span>\
                                <textarea class="billing_right_tit_textarea borderNone" name="medicineHistory" placeholder="请输入宝宝用药史" readonly></textarea>\
                            </div>\
                            <div class="billing_right_tit hidden">\
                                <span class="billing_right_tit_fontSize">实验室及辅助检查</span>\
                                <textarea class="billing_right_tit_textarea borderNone" name="laboratoryHistory" placeholder="请输入实验室及辅助检查" readonly></textarea>\
                            </div>\
                        </div>\
                        <ul class="billing_right_tit billing_right_tipBtn hidden">\
                            <li  class="hasChoiceAct" rel="on"><i class="icon iconfont icon-jiahao"></i>个病人史</li>\
                            <li  class="hasChoiceAct" rel="on"><i class="icon iconfont icon-jiahao"></i>高烧惊厥史</li>\
                            <li  class="hasChoiceAct" rel="on"><i class="icon iconfont icon-jiahao"></i>用药史</li>\
                            <li  class="hasChoiceAct" rel="on"><i class="icon iconfont icon-jiahao"></i>实验室及辅助检查</li>\
                        </ul>\
                        <input id="keepForm" class="billing_keep hidden" type="button" value="保存">\
                    </form>';
        return _html
    },
    home_billing_rightInfo:function(data){
        var _data=data
        var _html = '<div class="listContainsTitle bottomLine">\
                        <span>消费清单</span> <span class="clearAll ">清空页面</span>\
                        </div>\
                        <div class="baseInfo bottomLine zcwrap">\
                            <div class="topHeadPart bottomLine clearfix">\
                                <div class="headPortrait fl">\
                                    <img src="'+_data.userImg+'">\
                                </div>\
                                <div class="fl" style="padding: 0.4rem;padding-bottom: 0;">\
                                    <div style="height: 1.5rem;">'+_data.userName+'</div>\
                                    <div>'+_data.userPhone+'</div>\
                                </div>\
                                <span class="arrowDown"><i class="icon iconfont icon-xiajiantou"></i></span>\
                            </div>\
                            <div class="patientList" id="babyListBorder"></div>\
                            <div class="addChildrenBtn bottomLine likeBlue" id="addIllPeople">+新增宝宝 </div>\
                            <div class="newAddBtn" style="padding-top:0.5rem">\
                                <div class="fl">\
                                    <select id="illSelectleft"  class=" select_arrow" style="margin-top: 0.5rem" disabled>\
                                        <option selected>请选择</option>\
                                    </select>\
                                </div>\
                                <div class="fr">\
                                    <span class="patientDesc">接诊推拿师</span>\
                                    <select style="width: 8rem;" id="illSelectRight" class="patientDesc select_arrow">\
                                    <option selected>请选择</option>\
                                    </select>\
                                </div>\
                            </div>\
                            <div class="patientinfo js_patientinfo hidden">\
                                <div class="row form-inline js_lastTime_wrap">\
                                    <span class="col-sm-3 nopd form-text font_left">最近就诊:</span>\
                                    <div class="col-sm-9 nopd">\
                                        <span class="form-text js_lastTime" ></span>\
                                    </div>\
                                </div>\
                                <div class="row form-inline js_tips1_wrap">\
                                    <div class="col-sm-6">\
                                        <a href="javascript:void(0)" rel="1" class="tipsbtn js_tipsbtn">调理身体</a>\
                                    </div>\
                                    <div class="col-sm-6">\
                                        <a href="javascript:void(0)" rel="2" class="tipsbtn js_tipsbtn">保健预防</a>\
                                    </div>\
                                </div>\
                                <div class="row form-inline js_tips2_wrap">\
                                    <div class="col-sm-6">\
                                        <a href="javascript:void(0)" rel="3" class="tipsbtn js_tipsbtn">继续调理</a>\
                                    </div>\
                                    <div class="col-sm-6">\
                                        <a href="javascript:void(0)" rel="4" class="tipsbtn js_tipsbtn active">开始新病程</a>\
                                    </div>\
                                </div>\
                                <div class="row form-inline couponOption">\
                                    <label class="col-sm-3 nopd">预约备注：</label>\
                                    <textarea class="col-sm-9 form-control js_bookingDesc" name="bookingDesc" placeholder="请输入预约备注"></textarea>\
                                </div>\
                                <div class="row js_saveBooking_wrap">\
                                    <div class="col-sm-8"></div>\
                                    <div class="col-sm-4 text-right nopd">\
                                        <button class="btn btn-sm btn-info js_saveBooking">保存</button>\
                                    </div>\
                                </div>\
                            </div>\
                            <div class="js_project_wrap" id="js_serviceBox" rel="1"></div>\
                            <div class="row achItem1 hidden js_sumtit" style="line-height: 3rem;">\
                                <div class="col-sm-6 font_left">\
                                    <span class="patientDesc">小计金额</span>\
                                </div>\
                                <div class="col-sm-6 font_right" id="PayNum">\
                                    ￥<span>0</span>\
                                </div>\
                            </div>\
                            <!--<div class="clearfix eachItem1 hidden js_sumtit" style="line-height: 3rem;">\
                                <div class="fl">\
                                    <span class="patientDesc">小计金额</span>\
                                </div>\
                                <div id="PayNum" class="fr">\
                                    ￥<span>0</span>\
                                </div>\
                            </div>-->\
                            <div class="js_project_wrap" id="addProductBox_list" rel="2" style="width:100%"></div>\
                        </div>\
                        <div class="bottomList_home">\
                            <!--<div class="footerWrapper">\
                                <div class="isHadCoupon likeBlueBg likeBlue clearfix">\
                                    <div class="fl" style="color:#7c7c7c;"> 优惠券</div>\
                                    <select class="fr likeBlueBg select_choice">\
                                        <option>不使用优惠券</option>\
                                    </select>\
                                </div>\
                                <div></div>\
                            </div>-->\
                            <div class="payWrapper clearfix">\
                                <div class="fl">\
                                    待支付： ￥<span class="likeRed">0</span>\
                                </div>\
                                <div class="fr">\
                                    <div class="otherpay_wrap hidden">\
                                        <p class="otherpay_wrap_btn">他人代付</p>\
                                    </div>\
                                    <button class="btn btn-sm saveBtnPay btn-rose bg_0 font_7c">保存</button>\
                                    <button class="btn btn-sm gatheringBtn btn-info">收款</button>\
                                </div>\
                            </div>\
                        </div>'
        return _html
    }
}

// ---------------- 事件绑定 ----------------------

// 切换菜单
$('.Baby_Healthy_home_billing_left_dl>dd').on("click",function(){
    var ddIndex = $(this).index();
    if (DocData.bookingStatus == 4 && ddIndex!="2") {
        baseFn.infoDialog('订单已完成，只能完善病历，无法进行其他操作！');
        return false;
    }
    if($(this).attr('flage')=='true'){
        if(!baseFn.notNull(DocData.bookingInfo.bookingId) && !baseFn.notNull(DocData.bookingInfo.patientId)){
            baseFn.infoDialog('请选择或添加一位宝宝');
            return false
        }else if(!baseFn.notNull(DocData.bookingInfo.bookingId) && baseFn.notNull(DocData.bookingInfo.patientId)){
            baseFn.infoDialog('请保存预约类型');
            return false
        }else if(!baseFn.notNull(DocData.bookingInfo.patientId) && ddIndex != "1"){
            baseFn.infoDialog('请选择或添加一位宝宝');
            return false
        // }else if(!baseFn.notNull(DocData.bookingInfo.treatmentId) && (ddIndex == "4" || ddIndex == "5")){
        //     baseFn.infoDialog('您还没有填写病历！')
        //     return false
        }else if(baseFn.notNull(DocData.bookingInfo.treatmentId) && baseFn.notNull(DocData.bookingInfo.bookingType) && DocData.bookingInfo.bookingType == 0 && (ddIndex == "4" || ddIndex == "5") && !DocData.bookingInfo.canSelGoods){
            baseFn.infoDialog('请将病历填写完整')
            return false
            
        // }else if(DocData.bookingInfo.bookingType == 0 && !DocData.bookingInfo.treatmentOk && (ddIndex == "4" || ddIndex == "5")){
        //     baseFn.infoDialog('选择“调理身体”时需要将病历填写完整')
        //     return false
        }
        if(ddIndex=="2" || ddIndex=="4" || ddIndex=="5"){
            var allergyHistory = $("textarea[name=allergyHistory]").val();
            var userHistory = $("textarea[name=userHistory]").val();
            var feverHistory = $("textarea[name=feverHistory]").val();
            var medicineHistory = $("textarea[name=medicineHistory]").val();
            if (!baseFn.notNull(allergyHistory) || !baseFn.notNull(userHistory) || !baseFn.notNull(feverHistory) || !baseFn.notNull(medicineHistory)) {
                baseFn.infoDialog('请完善"既往病史档案"中的必填项');
                return false
            }
        }
        $(this).addClass("bgc_alert").siblings().removeClass("bgc_alert");
        if(ddIndex=="1"){
            $('.Baby_Healthy_home_billing_right_center').eq(1).removeClass('hidden').siblings(".Baby_Healthy_home_billing_right_center").addClass("hidden");
        }else if(ddIndex=="2"){
            if(baseFn.notNull(DocData.bookingInfo.patientId)){
                $('.Baby_Healthy_home_billing_right_center').eq(2).removeClass('hidden').siblings(".Baby_Healthy_home_billing_right_center").addClass("hidden");
                getBabyListIllHandle()
                
            }
        }else if(ddIndex=="4"){
            if(baseFn.notNull(DocData.bookingInfo.bookingId)){
                $('.Baby_Healthy_home_billing_right_center').eq(3).removeClass('hidden').siblings(".Baby_Healthy_home_billing_right_center").addClass("hidden");
            }
        }else if(ddIndex=="5"){
            if(baseFn.notNull(DocData.bookingInfo.bookingId)){
                $('.Baby_Healthy_home_billing_right_center').eq(4).removeClass('hidden').siblings(".Baby_Healthy_home_billing_right_center").addClass("hidden");
            }
        }
        
    }
});

// 清空全部
$('.consumeListContains').on('click',".clearAll",function(){
    $('.Baby_Healthy_home_billing_left_dd').attr('flage',false).removeClass('bgc_alert');
    $(this).parents(".consumeListContains").addClass('hidden').siblings('.serachSelect').removeClass('hidden').siblings('.noticeImg').removeClass('hidden');
    $('.Baby_Healthy_home_billing_right_center').eq(0).removeClass('hidden').siblings(".Baby_Healthy_home_billing_right_center").addClass("hidden");
    $('.js_storeelm').find('.storeelm_checkbox').removeClass('checkBox_checked')
    baseFn.goPath('gotoFastOrder')
});

//优惠券使用
$('.consumeListContains').on('change','.select_choice',function(){
    var _val = $(this).val()
    var _cardInfo = DocData.couponList.filter(function(val){
        return val.cardId == _val
    })
    if(_cardInfo.length == 0){
        DocData.couponId=undefined
        DocData.couponMoney=0
    }else{
        DocData.couponId = _cardInfo[0].cardId;
        if(_cardInfo[0].cardType == 1 || _cardInfo[0].cardType == 3){
            DocData.couponMoney= Number(_cardInfo[0].discountCosts)
        }else if(_cardInfo[0].cardType == 2){
            var _seviceelm = $('.js_project_wrap[rel=1]').find('.newAddBtn[rel='+_cardInfo[0].serviceId+']')
            if(_seviceelm && !_seviceelm.hasClass('cardoff')){
                DocData.couponMoney= Number(_seviceelm.data('cost'))
            }else{
                DocData.couponMoney= 0
            }
        }
    }
    $('.bottomList_home').find('.likeRed').text((DocData.pay-DocData.couponMoney)<0?0:(DocData.pay-DocData.couponMoney))
    DocData.canPay = false
})

//搜索框
$('.billing_right_right_btn_searchbox').select2({
    placeholder: '请输入宝宝姓名',
    language:{
        noResults:function(){return '<span class="font_blue">没有查询到宝宝！</span>'},
        searching:function(){return '查询中。。。'}
    },
    allowClear: true,
    ajax: {
        url: baseUrl.base+"patient/selectPatient",
        type: "get",
        dataType: 'json',
        data: function (params) {
            return {
                patientName: params.term
            }
        },
        processResults: function (data) {
            var dataResult =[];
            var dataItem = data.results;
            for(var i=0;i<dataItem.length;i++){
                dataItem[i].id=dataItem[i].patientId;
                dataItem[i].text=dataItem[i].patientName + '-' +dataItem[i].patientPhone;
                dataResult.push(dataItem[i]);
            }
            return {
                results:dataResult,
            }
        },
        formatResult: function formatRepo(repo){return repo.text;}, // 函数用来渲染结果
        formatSelection: function formatRepoSelection(repo){return repo.text;} // 函数用于呈现当前的选择
    },
    templateResult:function(state){
        // console.log(state)
        if(!state.loading && baseFn.notNull(state.patientPhone)){
            var _html = '<div class="zc_search_select2">'
            _html += '<div class="row" style="padding-right:0">'+
                '<div class="col-sm-4">' +
                '<div>'+state.patientName + (state.patientGender==0?' 男 ':' 女 ') + (baseFn.notNull(state.patientAge)?state.patientAge:0)+'岁'+'</div>'+
                '<div>'+state.patientPhone+'</div>'+
                '</div>'
            _html += '<div class="col-sm-4">' +
                '<div style="text-align:center">第二会员电话</div>' +
                '<div style="text-align:center">'+((baseFn.notNull(state.patientPhones) && state.patientPhones != '空')?state.patientPhones:'未绑定')+'</div>' +
                '</div>'
            _html += '<div class="col-sm-4">' +
                '<div style="text-align:center">第三会员电话</div>' +
                '<div style="text-align:center">'+((baseFn.notNull(state.patientPhoness) && state.patientPhoness != '空')?state.patientPhoness:'未绑定')+'</div>' +
                '</div>'
            _html += '</div></div>'
            return _html
        }

    },
    escapeMarkup: function (markup) {return markup; }, // 自定义格式化防止xss注入
    minimumInputLength: function(e){
        var _val = e.term;
        if(/^[\u4e00-\u9fa5]{1,5}$/.test(_val)){
            return 1
        }else{
            return 3
        }
    }//最少输入多少个字符后开始查询
});

$(".billing_right_right_btn_searchbox").on("select2:select",function(e){

    DocData.patientInfo = e.params.data;
    DocData.bookingInfo.patientId = DocData.patientInfo.patientId
    DocData.bookingInfo.userId = DocData.patientInfo.userId
    DocData.orderId = ''
    getUserMsgHandle(DocData.bookingInfo.userId);
})

$('.consumeListContains').on('click','.saveBtnPay',function(){
    var $this = $(this)
    if($(this).attr('rel') == 1){
        baseFn.infoDialog('订单正在提交中，不要重复操作')
        return false
    }else{
        $(this).attr('rel',1)
    }
    orderDialog = baseFn.dialog({
        content:'确认保存该订单？',
        ok:function(){
            // if(DocData.bookingInfo.bookingType == 0 && !DocData.bookingInfo.treatmentOk){
            //     baseFn.infoDialog('选择“调理身体”时需要将病历填写完整')
            //     return false
            // }
            DocData.saveOrder(false,'.saveBtnPay')
            
        },
        cancel:function(){
            $this.attr('rel',0)
        }
    })
})

//收款
$('.consumeListContains').on('click','.gatheringBtn',function(){
    var $this = $(this)
    if(DocData.orderId != ''){
        if(DocData.canPay){
                $.get(baseUrl.base+baseUrl.order+'selectOrderInfo',{orderId:DocData.orderId},function(res){
                    if(res.code==0){
                        if($this.attr('rel') == 1){
                            baseFn.infoDialog('正在付款中，不要重复操作')
                            return false
                        }else{
                            $this.attr('rel',1)
                        }
                        DocData.initOrder(res.results)
                        DocData.orderData = res.results
                        DocData.couponId = res.results.orderInfo.couponId
                        if(DocData.otherPay && time != ''){
                            //代付
                            $('.js_payOrderPhone').val('')
                            $('.js_checkId').val('')
                            window.clearInterval(time)
                            $('.js_getCheckBtn').removeClass('disabled').text('获取验证码')
                            time = '';
                            _time = 60;
                        }
                        var _cardList = DocData.orderData.cardList,canPay = true
                        for(var x=0;x<_cardList.length;x++){
                            if(!DocData.arrFilter(DocData.userCardList,'cardId',_cardList[x].cardId,'','out')){
                                canPay = false
                            }
                            
                        }
                        if(canPay && DocData.bookingStatus != 4){
                            baseFn.dialog({
                            width:'40em',
                            height:'65vh',
                            title:'收银台',
                            content:$('.gatheringlist'),
                            okValue:'确认收款',
                            ok:function(){
                                
                                var _upDatas={
                                    orderId:DocData.orderId,
                                    cashierId:DocData.cashierId
                                }
                                if(DocData.otherPay){
                                    var _txt=''
                                    _upDatas.check = $('input.js_checkId').val()
                                    _upDatas.userPhone = $('input.js_payOrderPhone').val()
                                    // if(!baseFn.notNull(_upDatas.check)){
                                    //     _txt = '请输入验证码'
                                    // }else
                                    if(!baseFn.notNull(_upDatas.userPhone)){
                                        _txt = '请输入代付人手机号'
                                    }else if(!/^13[0-9]{9}$|14[0-9]{9}|17[0-9]{9}|15[0-9]{9}$|18[0-9]{9}$/.test(_upDatas.userPhone)){
                                        _txt = '请输入正确的手机号格式'
                                    }
                                    if(baseFn.notNull(_txt)){
                                        baseFn.infoDialog(_txt)
                                        return false
                                    }
                                }
                                if(baseFn.notNull(DocData.payWay) && !baseFn.notNull(DocData.payUserId)){
                                    _upDatas.payWay = DocData.payWay
                                }
                                if(baseFn.notNull(DocData.payWays) && !baseFn.notNull(DocData.payUserId)){
                                    _upDatas.payWays = DocData.payWays
                                }
                                if(baseFn.notNull(DocData.payWay) && DocData.otherPay){
                                    _upDatas.payWay = 7
                                }
                                if(baseFn.notNull(DocData.payWays) && DocData.otherPay){
                                    _upDatas.payWays = 7
                                }
                                $.post(baseUrl.base+baseUrl.order+'submitOrderInfo',_upDatas,function(res){
                                    if(res.code ==0){
                                        $this.attr('rel',0)
                                        var _rtTxt='支付完成';
                                        if(DocData.payService != 0 || DocData.payGoods != 0){
                                            DocData.userInfo.userAccount = (Number(DocData.userInfo.userAccount) - Number(DocData.payService) - Number(DocData.payGoods))
                                            _rtTxt = '支付完成，账户余额还有'+DocData.userInfo.userAccount +'元。'
                                            DocData.payGoods = 0
                                            DocData.payService = 0
                                        }
                                        
                                        baseFn.infoDialog(_rtTxt,function(){
                                            window.location.href=DocData.orderURL
                                        }, 8000)
                                        
                                    }else if(res.code == 60007){
                                        // baseFn.dialog({
                                        //     title:'提示',
                                        //     content:'该订单优惠券已用，请更新订单后付款'
                                        // })
                                        baseFn.infoDialog('该订单优惠券已用，请更新订单后付款')
                                        $this.attr('rel',0)
                                        couponlist();
                                        DocData.canPay=false
                                        DocData.couponId='';
                                        DocData.orderData.orderInfo.couponId=''
                                    }else{
                                        $this.attr('rel',0)
                                        baseFn.infoDialog(res.msg)
                                    }
                                },'json').complete(function(){
                                    $this.attr('rel',0)
                                })
                            },
                            cancel:function(){
                                $this.attr('rel',0)
                            }
                        })
                        }else{
                            if (DocData.bookingStatus != 4) {
                                baseFn.infoDialog('该订单已选推拿服务中，存在计次卡次数用完但选择了使用计次卡的情况，系统已做相应变更，请先保存订单后再继续操作。')
                            }
                        }
                        DocData.canRenderOrderList()
                    }else{
                        baseFn.infoDialog(res.msg)
                    }
                },'json')
            
        }else{
            var d=baseFn.dialog({
                content:'订单有修改，是否保存后进行收款？',
                ok:function(){
                    DocData.saveOrder(true,'.saveBtnPay')
                },
                cancel:function(){}
            })
        } 
    }else{
        var d=baseFn.dialog({
            content:'订单未保存，是否保存后进行收款？',
            ok:function(){
                DocData.saveOrder(true,'.saveBtnPay')
            },
            cancel:function(){}
        })
    }
})

//代付按钮
$('.consumeListContains').on('click','.otherpay_wrap_btn',function(){
    
    if($(this).hasClass('active')){
        $(this).removeClass('active')
        DocData.otherPay = false
        DocData.payWay = 0
        DocData.payWays = 0
        $('.payelm').removeClass('active')
        $('.payelm[rel="0"]').addClass('active')
    }else{
        $(this).addClass('active');
        DocData.otherPay = true;
        DocData.payWay = 7
        DocData.payWays = 7
        
    }  
})

$('.payelm').on('click',function(){
    var _parent = $(this).parents('.zccardelm')
    _parent.find('.payelm').removeClass('active')
    $(this).addClass('active')
    if(_parent.attr('rel') == 1){
        DocData.payWay=$(this).attr('rel')//服务支付方式
    }else{
        DocData.payWays=$(this).attr('rel')//商品支付方式
    }
})
/*代付*/
//绑定代付
// $('.js_checkBtn').on('click',function(){
//     var _upDatas={
//         userPhone:$('input.js_payOrderPhone').val(),
//         check:$('input.js_checkId').val(),
//         orderId:DocData.orderId
//     }
//     var _txt=''
//     if(!baseFn.notNull(_upDatas.orderId)){
//         _txt = '没有订单，请先保存订单'
//     }else if(!baseFn.notNull(_upDatas.check)){
//         _txt = '请输入验证码'
//     }else if(!baseFn.notNull(_upDatas.userPhone)){
//         _txt = '请输入代付人手机号'
//     }else if(!/^13[0-9]{9}$|14[0-9]{9}|17[0-9]{9}|15[0-9]{9}$|18[0-9]{9}$/.test(_upDatas.userPhone)){
//         _txt = '请输入正确的手机号格式'
//     }
//     if(baseFn.notNull(_txt)){
//         baseFn.infoDialog(_txt)
//         return false
//     }
//     baseFn.$post({
//         url:'order/savePayOrder',
//         data:_upDatas,
//         canNull:true,
//         calFn:function(res){
//             $('.gatheringlist').find('.js_paywrap_other_new').addClass('hidden')
//             $('.gatheringlist').find('.js_paywrap_other_old').removeClass('hidden')
//             $('.gatheringlist').find('.js_paywrap_other_old').find('.js_payOrderName').text(res.payUserName)
//             $('.gatheringlist').find('.js_paywrap_other_old').find('.js_payOrderPhone').text(res.payUserphone)
//             DocData.payUserId = res.payUserId
//             DocData.otherCanPay = true
//         }
//     })
    
// })

//获取验证码
var time = '',_time=60
$('.js_getCheckBtn').on('click',function(){
    var _upDatas={
        orderId:DocData.orderId,
        userPhone:$('input.js_payOrderPhone').val()
    }
    var _txt=''
    if(!baseFn.notNull(_upDatas.orderId)){
        _txt = '没有订单，请先保存订单'
    }else if(!baseFn.notNull(_upDatas.userPhone)){
        _txt = '请输入代付人手机号'
    }else if(!/^13[0-9]{9}$|14[0-9]{9}|17[0-9]{9}|15[0-9]{9}$|18[0-9]{9}$/.test(_upDatas.userPhone)){
        _txt = '请输入正确的手机号格式'
    }
    if(baseFn.notNull(_txt)){
        baseFn.infoDialog(_txt)
        return false
    }
    var $this = $(this)
    if($this.hasClass('disabled')){
        return false
    }else{
        baseFn.$post({
            url:'order/replacePayOrder',
            data:_upDatas,
            canNull:true,
            calFn:function(res){
                baseFn.infoDialog('成功发送验证码')
                $this.addClass('disabled')
                time = setInterval(function(){
                    $this.text('还有'+_time+'秒')
                    _time --
                    if(_time == '0'){
                        _time = 60;
                        $this.removeClass('disabled').text('重新获取')
                        window.clearInterval(time)
                        time=''
                    }
                },1000)
            }
        })
    } 
})

/* 宝宝基本信息 */
// 新增宝宝 按钮
$('.consumeListContains').on('click','#addIllPeople',function(){
    DocData.patientInfo={}
    DocData.bookingInfo.patientId = ''
    DocData.bookingInfo.canSave = false
    $('.js_saveBooking_wrap').removeClass('hidden')
    var addNewHtml = baseHtml.home_billing_patientInfo({
        patientImg:baseUrl.patientImg
    })
    $('.billing_right_center_details').html(addNewHtml);
    DocData.renderPatientInfo({},true)
    birthDay();//初始化日期
    $('.editorInfo').addClass('hidden')
});
// 编辑宝宝 按钮
$('.billing_right_center_details').on('click','.editorInfo',function(){
    if($(this).attr('rel')=="on"){
        //點擊取消
        $(this).attr('rel','off').text("编辑");
        DocData.renderPatientInfo(true,false)
        //病史档案渲染
        $('#caseOfIlliness>.billing_right_tit').each(function (i, obj) {
            if(!baseFn.notNull( $(obj).find('textarea').text()) && $(obj).find('textarea').attr('name') != 'justNowHistory'){
                $(obj).addClass('hidden');
            }
        })
    }else{
        //点击编辑
        $(this).attr('rel','on').text('取消');
        DocData.renderPatientInfo(true,true)
    }
});
// 提交（新增或编辑）宝宝基本信息
$('.Baby_Healthy_home_billing_right_center').on('click','#keepForm',function(){
    // 校验
    var userName = $("input[name=userName]").val();
    if(userName=='undefined'|| userName==''){
        alert('姓名不能为空');
        return false;
    }
    // var userHeight=$('input[name=userHeight]').val();
    // if(userHeight=='undefined'||userHeight==''){
    //     alert('身高不能为空');
    //     return false;
    // }
    // var userBodyWeight=$('input[name=userBodyWeight]').val();
    // if(userBodyWeight=='undefined'||userBodyWeight==''){
    //     alert('体重不能为空');
    //     return false;
    // }
    // var userAddress=$('input[name=userAddress]').val();
    // if(userAddress=='undefined'||userAddress==''){
    //     alert('住址不能为空');
    //     return false;
    // }
    // var textareaText = $('.billing_right_tit_textarea').text();
    // if(textareaText==null||textareaText=='undefined'){
    //     textareaText = '无';
    // }

    var allergyHistory = $("textarea[name=allergyHistory]").val();
    if(allergyHistory=='undefined'|| allergyHistory==''){
        alert('过敏史不能为空');
        return false;
    }

    var userHistory = $("textarea[name=userHistory]").val();
    if(userHistory=='undefined'|| userHistory==''){
        alert('个人病史不能为空');
        return false;
    }

    var feverHistory = $("textarea[name=feverHistory]").val();
    if(feverHistory=='undefined'|| feverHistory==''){
        alert('高烧惊厥史不能为空');
        return false;
    }

    var medicineHistory = $("textarea[name=medicineHistory]").val();
    if(medicineHistory=='undefined'|| medicineHistory==''){
        alert('用药史不能为空');
        return false;
    }

    var _url = 'savePatientInit'
    if(baseFn.notNull(DocData.patientInfo.patientId)){
        _url = 'updatePatientInit'
        $('#baseForm').find('input[name=subclinicId]').val(DocData.subclinicId)
        $('#baseForm').find('input[name=doctorId]').val(DocData.doctorId)
        $('#baseForm').find('input[name=userId]').val(DocData.userInfo.userId)
        $('#baseForm').find('input[name=bookingId]').val(baseFn.notNull(DocData.bookingInfo.bookingId)?DocData.bookingInfo.bookingId:null)
        $('#baseForm').find('input[name=patientId]').val(baseFn.notNull(DocData.patientInfo.patientId,true)?DocData.patientInfo.patientId:null)
    }else{
        $('#baseForm').find('input[name=userId]').val(DocData.userInfo.userId)
    }
    baseFn.$post({
        url:baseUrl.patient+_url,
        data:$('#baseForm').serialize(),
        canNull:true,
        calFn:function(res){
            if(!baseFn.notNull(DocData.patientInfo.patientId)){
                baseFn.infoDialog('成功添加')
                DocData.bookingInfo.patientId = res.patientId
                DocData.patientInfo={
                    patientId:res.patientId
                }
            }else{
                baseFn.infoDialog('编辑成功')
            }
            getChildrenListHandle(DocData.userInfo.userId);
        }
    })
})
// 3.切换宝宝-并获取基础数据（选择宝宝，切换预约类型等操作时）DocData.upBookingInfo
$('.consumeListContains').on('click','.patientList>.eachItem',function() {
    if($(this).attr('rel') == 'nochange'){
        return false
    }
    var babyId = $(this).attr('rel'),_ids=$(this).data('ids'),_tempBookingType = baseFn.notNull(DocData.patientGroup[_ids].bookingType)?DocData.patientGroup[_ids].bookingType:0,_tempIsAdd=baseFn.notNull(DocData.patientGroup[_ids].isAdd)?DocData.patientGroup[_ids].isAdd:1;
    $(this).addClass('active').siblings().removeClass('active');
    $('#firstId').addClass("bgc_alert").siblings().removeClass("bgc_alert");
    baseFn.$get({
        url: "patient/selectPatientInit",
        data: {
            'patientId': babyId
        },
        canNull:true,
        calFn:function(res){
            if(baseFn.notNull(res.patientInit)){
                /* #regoin 宝宝基础信息数据 */
                $('.editorInfo').removeClass('hidden');//可编辑基本信息数据
                DocData.patientInfo = res.patientInit;//更改宝宝信息
                var _infoData={
                    bookingId:baseFn.notNull(DocData.bookingInfo.bookingId,true),
                    doctorId:DocData.doctorId,
                    subclinicId:DocData.subclinicId,
                    userId:$("input[name=userIds]").val(),
                    patientImg:baseFn.notNull2(DocData.patientInfo.patientImg,true,baseUrl.patientImg),
                    patientId:babyId,
                    patientName:baseFn.notNull2(DocData.patientInfo.patientName,true,'--'),
                    patientBirthday:baseFn.notNull2(DocData.patientInfo.patientBirthday,true,'--'),
                    patientGender:baseFn.notNull2(DocData.patientInfo.patientGender,true,0),
                    patientHeight:baseFn.notNull2(DocData.patientInfo.patientHeight,true,'--'),
                    patientAddress:baseFn.notNull2(DocData.patientInfo.patientAddress,true,'--'),
                    patientBodyWeight:baseFn.notNull2(DocData.patientInfo.patientBodyWeight,true,'--'),
                    userSource:baseFn.notNull2(DocData.patientInfo.userSource,true,'--')
                }
                $('.js_patientinfo_wrap').html(baseHtml.home_billing_patientInfo(_infoData));
                var patientHistory = res.patientHistory;//病史信息
                //病史信息
                if(patientHistory==null) {
                    $('#caseOfIlliness>.billing_right_tit').eq(0).removeClass('hidden');
                    $('#caseOfIlliness>.billing_right_tit').eq(0).find('textarea').text('无');
                }else{
                    var map = [
                        patientHistory.allergyHistory,
                        patientHistory.userHistory,
                        patientHistory.feverHistory,
                        patientHistory.medicineHistory,
                        patientHistory.laboratoryHistory
                    ];
                    $('#caseOfIlliness>.billing_right_tit').each(function (i, obj) {
                        if (baseFn.notNull(map[i])){
                            $(obj).removeClass('hidden').find('textarea').text(map[i]);
                            if(i!=0){
                                $('.hasChoiceAct').eq(i-1).addClass('bgc_alert').attr('rel','off');
                            }
                        }
                    });
                }
                birthDay();//初始化日期
                //订单信息
                var orderList = res.orderList;
                if(baseFn.notNull(orderList) && orderList.length>0){
                    $('#illList').removeClass('hidden')
                }else{
                    $('#illList').addClass('hidden')
                }

                //就诊记录渲染
                $('select[name=userGender]').val(_infoData.patientGender)
                DocData.renderPatientInfo({},false)
                DocData.renderPatientSelList()
                /* #endregoin 宝宝基础数据 */
                //有预约单的时候 该预约单的宝宝的预约类型数据要和预约单统一
                if(baseFn.notNull(DocData.bookingInfo) && baseFn.notNull(DocData.bookingInfo.bookingId) && DocData.bookingInfo.patientId == DocData.patientInfo.patientId){
                    DocData.patientInfo.isAdd = _tempIsAdd
                    DocData.patientInfo.bookingType = _tempBookingType
                }else{
                    DocData.patientInfo.bookingType = DocData.bookingInfo.bookingType = _tempBookingType
                    DocData.patientInfo.isAdd = DocData.bookingInfo.isAdd = _tempIsAdd
                }
            }else{
                DocData.bookingInfo.bookingType = 0
                DocData.bookingInfo.isAdd = 1
            }
            treatmentTest(DocData.bookingInfo.bookingType)
            // console.log(_tempBookingType)
            $('.js_tipsbtn').removeClass('active')
            $('.js_tipsbtn').removeClass('disabled')
            //预约类型初始化
            if(baseFn.notNull(DocData.patientInfo.lastTime)){
                $('.js_lastTime').text(baseFn.timestampToTime(DocData.patientInfo.lastTime))
            }else{
                $('.js_lastTime').text('最近无就诊')
            }
            if(baseFn.notNull(DocData.bookingInfo.bookingDesc)){
                $('.js_bookingDesc').val(DocData.bookingInfo.bookingDesc)
            }
            $('.js_tips1_wrap').find('.js_tipsbtn[rel='+(Number(DocData.bookingInfo.bookingType)+1)+']').addClass('active')
            $('.js_tips2_wrap').find('.js_tipsbtn[rel='+(Number(DocData.bookingInfo.isAdd)+3)+']').addClass('active')
            if(DocData.bookingInfo.bookingType == 1){
                $('.js_tips2_wrap').addClass('hidden')
            }else{
                $('.js_tips2_wrap').removeClass('hidden')
            }
            if(baseFn.notNull(DocData.patientInfo.bookingType) && DocData.patientInfo.bookingType == 1){
                $('.js_tipsbtn[rel=3]').addClass('disabled')
            }
            if(DocData.bookingInfo.canSave){
                DocData.upBookingInfo()
            }
            if(baseFn.notNull(DocData.bookingInfo.bookingId) && baseFn.notNull(DocData.patientInfo.patientId)){
                DocData.bookingInfo.canSave = true
            }else{
                DocData.bookingInfo.canSave = false
            }
            if(baseFn.notNull(DocData.bookingInfo.bookingId)){
                $('.js_saveBooking_wrap').addClass('hidden')
            }else{
                $('.js_saveBooking_wrap').removeClass('hidden')
            }
            DocData.caseListDLFn()
            if(baseFn.notNull(DocData.orderId)){
                $('.patientList>.eachItem').attr('rel','nochange')
            }
            if (DocData.bookingStatus == 4) {
                $("dd[rel=2]").trigger("click");
                $("#rightDiv").css("pointer-events","none");
            }
        }
    })

});
// 添加/删除病史
$('.billing_right_center_details').on('click','.hasChoiceAct',function(){
    index = $(this).index();
    if($(this).attr('rel')=="on"){
        $(this).attr('rel',"off").addClass('bgc_alert');
        $('.billing_right_tit').each(function(i,n){
            if((i-1)==index){
                $(n).removeClass('hidden');
            }
        })
    }else if($(this).attr('rel')=="off"){
        $(this).attr('rel',"on").removeClass('bgc_alert');
        $('.billing_right_tit').each(function(i,n){
            if((i-1)==index){
                $(n).addClass('hidden');
                $(n).find('textarea.billing_right_tit_textarea').val('')
            }
        })
    }
});

/*购买商品和服务*/
// 选中推拿
$('#tuinaList').on('click','.storeelm_checkbox',function(){
    var $this = $(this)
    var value = $this.val();
    if($(this).hasClass('checkBox_checked')){
        $('#js_serviceBox>.tuinaList').each(function(i,n){
            var newRel = $(n).find('.newAddBtn').attr('rel');
            if(value==newRel){
                $(n).remove();
            }
        });
        $(this).removeClass('checkBox_checked');
    }else{
        var $this = $(this)
        $this.addClass('checkBox_checked');

        var _data={
            value:value,//服务id或者商品id
            cardId:'',//卡id
            name:$this.parents('.storecnt').find('.tit').text(),
            cost:$this.parents('.storecnt').find('.tips span').text(),
            num:0,
            useCard:0
        }
        var countCard=DocData.userCardList.filter(function(val){
            return val.serviceId == value
        })

        //如果进入时是个有orderid的代付订单需要查询订单是否用了相关的计次卡
        if(baseFn.notNull(DocData.orderData) && DocData.orderData.cardList && DocData.orderData.cardList.length != 0){
            var _orderCard = DocData.arrFilter(DocData.orderData.cardList,'serviceId',value,'','out')
            if(_orderCard && _orderCard.length != 0 && DocData.arrFilter(DocData.orderData.cardList,'cardId',_orderCard[0].cardId,'','out')){
                countCard = _orderCard
            }
        }

        if(countCard.length !=0){
            _data.cardId = countCard[0].cardId
            _data.num = countCard[0].cardCount
        }
        DocData.renderGoodsCar('service',_data)
    }
    DocData.canPay=false
    sumLit()
})
// 使用计次卡
$('.consumeListContains').on('change','.js_serviceSelCard',function(){
    DocData.canPay = false ;
    if($(this).val() == 0){
        $(this).parents('.tuinaList').find('.newAddBtn').removeClass('cardoff')
    }else if($(this).val() == 1){
        $(this).parents('.tuinaList').find('.newAddBtn').addClass('cardoff')
    }
    sumLit()
})
// 选中商品
$('#productList').on('click','.storeelm_checkbox',function(){
    var value = $(this).val();
    if($(this).hasClass('checkBox_checked')){
        $('#addProductBox_list>.tuinaList').each(function(i,n){
            var newRel = $(n).find('.newAddBtn').attr('rel');
            if(value==newRel){
                $(n).remove();
            }
        });
        $(this).removeClass('checkBox_checked');
    }else{
        $(this).addClass('checkBox_checked');
        var _data={
            value:value,//服务id或者商品id
            name:$(this).parents('.storecnt').find('.tit').text(),
            cost:$(this).parents('.storecnt').find('.tips span').text(),
            num:1
        }
        DocData.renderGoodsCar('goods',_data)
    }
    DocData.canPay=false
    sumTotal()
})
// 加减购物车
$('.Baby_Healthy_home_billing_right_right').on('click','.addNum',function(){
    var smallText = $(this).siblings('.jishuNum').text();
    var money =$(this).parent().siblings('.milk').text();
    var newMoney = $(this).parent().siblings('.moneyNumberTip').text();
    if($(this).attr('rel')==1){
        smallText++;
        $(this).siblings('.jishuNum').text(smallText);
        var newMoney =smallText*money;
        $(this).parent().siblings('.moneyNumberTip').text(newMoney);
    }else{
        if(smallText<=1){
            smallText = 1
            return false
        }else{
            smallText--;
        }

        var newMoney =newMoney-money;
        $(this).siblings('.jishuNum').text(smallText);
        $(this).parent().siblings('.moneyNumberTip').text(newMoney);
    }
    sumTotal()
    DocData.canPay=false
})

// 搜索服务
$("#serviceSearchBtn").on('click', '', function(){
    tuinaList($("#serviceNameSearchIpunt").val());
});

$("#serviceNameSearchIpunt").keydown(function(event) {
    if (event.keyCode == "13") {
        tuinaList($("#serviceNameSearchIpunt").val());
    }
});
// 搜索商品
$("#goodsSearchBtn").on('click', '', function(){
    productListHandle($("#goodsNameSearchIpunt").val());
});

$("#goodsNameSearchIpunt").keydown(function(event) {
    if (event.keyCode == "13") {
        productListHandle($("#goodsNameSearchIpunt").val());
    }
});

// 删除商品/服务
$('.consumeListContains').on('click','.deleteFr',function(){
    var _parent = $(this).parents('.js_project_wrap'),_checkboxRel=$(this).parents('.newAddBtn').attr('rel'),_type = _parent.attr('rel')
    var _pdom=$('#productList')
    if(_type == 1){
        _pdom = $('#tuinaList')
    }
    _pdom.find('input[value='+_checkboxRel+']').removeClass('checkBox_checked')
    $(this).parents('.tuinaList').remove();
    sumLit()
    DocData.canPay=false
})

// 添加主症
$('#addMainList').on('click',function(){
    var mainHtml = $('<div class="couponOption mainBox">\
            <label class="fast_formTipWidth heavy-weight"></label>\
            <select class="couponInput newWidthTip select_arrow mainList" type="text"></select>\
            <select class="couponInput newWidthTip select_arrow bandList" type="text"></select>\
        </div>');
    $(this).before(mainHtml);
    var _optionTxt='',_temp=[];
    $('.fast_caseOfIll').find('select.mainList').each(function(j,n){
        _temp.push($(n).val())
    })
    for(var i=0;i<DocData.newMainList.length;i++){
        var _cls = ''
        var _show = _temp.some(function(val){
            return val == DocData.newMainList[i].typeId
        })
        if(_show){_cls = 'hidden'}
        _optionTxt += '<option value="'+DocData.newMainList[i].typeId+'" class="'+_cls+'">'+DocData.newMainList[i].typeName+'</option>';
    }
    mainHtml.find('.mainList').append(_optionTxt)
    mainHtml.find('.mainList option[class!=hidden]').eq(0).prop('selected',true);
    var _vals = mainHtml.find('.mainList').val()
    var _child0=DocData.newMainList.filter(function(val){
        return val.typeId == _vals
    })[0].childList
    for(var j=0;j<_child0.length;j++){
        var _opts2 = '<option rel="'+_child0[j].diseaseScore+'"  value="' + _child0[j].descId + '">' + _child0[j].descName + '</option>';
        mainHtml.find('.bandList').append(_opts2)
    }
    filterSelectList()
    if(_temp.length == DocData.newMainList.length){
        $(this).addClass('hidden')
    }
});

//主症症状(二级) //同时改变一级
$('.fast_caseOfIll').on('change','.mainList',function(is,f){
    var $that =  $(this);
    $that.siblings('.bandList').empty();
    var typeId = $(this).find('option:selected').val();
    filterSelectList()
    var dataMsg = DocData.newMainList.filter(function(val){
        return val.typeId == typeId
    })[0].childList;
    for (var i = 0; i < dataMsg.length; i++) {
        var descName = dataMsg[i].descName;
        var descId = dataMsg[i].descId;
        var diseaseScore = dataMsg[i].diseaseScore;
        var optionHtml = '<option rel="'+diseaseScore+'"  value="'+descId+'">' + descName + '</option>';
        $that.parent().find('.bandList').append(optionHtml);
    }
});

// 获取诊断结论
baseFn.rpSelect('#selectConclusion',{
    url:baseUrl.base+"init/selectInitConclusionList",
    multiple:true,
    placeholder:'请选择结论',
    idKey:"conclusionId",
    textKey:'conclusionName',
    calFn:function(){
        DocData.clusion = true
        // if(!DocData.canRenderCase()){
        //     return false
        // }else{
        //     getBabyListIllHandle()
        // }
    }
})

// 提交病历fast_caseOfIll
$('.Baby_Healthy_home_billing_right_container').on('click',"#ill_saveBtnBox",function(){
    if($(this).attr('rel')=='off'){
        return false
    }
    if(baseFn.notNull(DocData.subclinicId)){
        DocData.doctorId = $('#illSelectRight').val()
    }else{
        baseFn.infoDialog('请选择门店')
    }
    var diseaseTime = $('input[name=diseaseTime]').val();//发病时间
    var diseaseInfo = $('input[name=diseaseInfo]').val();//主诉
    var treatmentRemarks = $('input[name=treatmentRemarks]').val();//自主配穴
    var treatmentOpinion = $('input[name=treatmentOpinion]').val();//诊断备注
    var treatmentImg = $('.Js_previewImgNew_1').val();//舌苔图片
    var faceImg = $('.Js_previewImgNew_2').val();//面部图片
    var handsImg = $('.Js_previewImgNew_3').val();//掌心图片
    var conclusion = $('#selectConclusion').select2("data");
    var conclusionArray =[];
    for(var i =0;i< conclusion.length;i++){
        var resultObj = {id:'',text:''};
        resultObj['id'] = conclusion[i].id;
        resultObj['text'] = conclusion[i].text;
        resultObj['conclusionId'] = conclusion[i].id;
        resultObj['conclusionName'] = conclusion[i].text;
        conclusionArray.push(resultObj);
    }
    var symptom=[];
    var pointArray=[];
    var _txt=''//非空验证
    $('.mainBox').each(function(i,n){//主症
        var resultObj = {userId:'',typeId:'',typeName:'',diseaseScore:0,diseaseId:'',diseaseName:'',isMain:'1'};
        var ids = $(n).find('.mainList').val();
        var text = $(n).find('.mainList>option:selected').text();
        var id1 = $(n).find('.bandList>option:selected').attr('value');
        var text1 = $(n).find('.bandList>option:selected').text();
        var diseaseScore = $(n).find('.bandList>option:selected').attr("rel");
        // var diseaseScore = $(n).find('.bandList>option[value='+id1+']').attr("rel");
        // console.log("diseaseScore="+diseaseScore);
        var isMain = $(n).find('input[name=isMain]').val();
        resultObj['diseaseId'] = id1;
        resultObj['diseaseName'] = text1;
        resultObj['typeId'] = ids;
        resultObj['typeName'] = text;
        resultObj['diseaseScore'] = diseaseScore;
        resultObj['userId'] = DocData.userInfo.userId;
        if (ids && ids != 0) {
            symptom.push(resultObj);
        }
    });
    if(symptom.length == 0){
        _txt ='请至少选择一项主症'
    }
    $('.fast_caseOfIll_select_box').each(function(i,n){
        var resultObj = {userId:'',typeId:'',typeName:'',diseaseScore:0,diseaseId:'',diseaseName:'',isMain:'0'};
        var ids = $(n).find('label').attr('value');
        var text = $(n).find('label').text();
        var text1 = $(n).find('select>option:selected').text();
        var id1 = $(n).find('select>option:selected').attr('value');
        var diseaseScore = $(n).find('select>option:selected').attr("rel");
        var isMain = $(n).find('input[name=isMain]').val();
        resultObj['diseaseId'] = id1;
        resultObj['diseaseName'] = text1;
        resultObj['typeId'] = ids;
        resultObj['typeName'] =text;
        resultObj['diseaseScore'] = diseaseScore;
        resultObj['userId'] = DocData.userInfo.userId;
        symptom.push(resultObj);
    });
    $('.bandleBox').each(function(i,n){//配穴
        if(baseFn.notNull($(n).find('.bodyPointList').val()) && $(n).find('.bodyPointList').val().length != 0){
            var _temps = $(n).find('.bodyPointList').select2("data");
            for(var j=0;j<_temps.length;j++){
                var resultObj = {typeId:'',typeName:'',pointId:'',pointName:'',userId:'',bookingId:'',patientId:'',doctorId:''};
                resultObj.typeId = $(n).find('.bandle_label').attr('value')
                resultObj.typeName = $(n).find('.bandle_label').text()
                resultObj.pointId = _temps[j].id
                // resultObj.diseaseId = _temps[j].id
                resultObj.pointName = _temps[j].text
                resultObj.userId = DocData.userInfo.userId
                resultObj.bookingId = DocData.bookingInfo.bookingId
                resultObj.patientId = DocData.patientInfo.patientId
                resultObj.doctorId = DocData.doctorId
                pointArray.push(resultObj)
            }
        }
    })

    var infoIds = [];
    $("input[watch=special]").each(function(i, n){
        if ($(n).hasClass("checkBox_checked")) {
            infoIds.push($(n).val());
        }
    });
    if (!$("#specialCheck").hasClass("checkBox_checked")) {
        var infoIds = [];
        DocData.checkResult = 0;
        DocData.realResult = 0;
        DocData.error = 0;
    }

    if(!baseFn.notNull(DocData.patientInfo.patientId)){
        _txt = '请选择一名宝宝'
    }else if(!baseFn.notNull(diseaseTime)){
        _txt = '请选择发病日期'
    }else if(!baseFn.notNull(diseaseInfo)){
        _txt = '请填写主诉'
    }else if(pointArray.length == 0){
        _txt = '请至少选择一个配穴'
    }else if(conclusionArray.length == 0){
        _txt = '请至少选择一项诊断结论'
    }else if(!baseFn.notNull(treatmentImg)){
        _txt = '请上传舌苔图片'
    }else if(!baseFn.notNull(faceImg)){
        _txt = '请上传正面全脸图片'
    }else if(!baseFn.notNull(handsImg)){
        _txt = '请上传掌心正面图片'
    }
    if(DocData.bookingInfo.bookingType == 0 && baseFn.notNull(_txt)){
        baseFn.infoDialog(_txt);
        return false;
    }
    var _upData={
        'userId':DocData.bookingInfo.userId,//用户id
        'patientId':DocData.patientInfo.patientId,//宝宝id
        'diseaseTime':diseaseTime,//发病时间
        'diseaseInfo':diseaseInfo ,//主诉
        'doctorId':DocData.doctorId ,//推拿师id
        'subclinicId':DocData.subclinicId ,//门店
        'bookingName':baseFn.notNull(DocData.bookingInfo.userName)?DocData.bookingInfo.userName:DocData.userName,
        'bookingPhone':baseFn.notNull(DocData.bookingInfo.userPhone)?DocData.bookingInfo.userPhone:DocData.userPhone,
        'bookingPhones':baseFn.notNull(DocData.bookingInfo.userPhones)?DocData.bookingInfo.userPhones:DocData.userPhones,
        'treatmentInit':'',//初步就诊
        'treatmentOpinion':treatmentOpinion ,//诊断备注
        'treatmentRemarks':treatmentRemarks ,//治疗意见（自主配穴）
        'treatmentImg':treatmentImg,//舌苔图片
        'faceImg':faceImg,//面部图片
        'handsImg':handsImg,//掌心图片
        'pointArray': JSON.stringify(pointArray),//穴位多选数组
        'diseaseArray': JSON.stringify(symptom),//病症多选数组
        'conclusionArray': JSON.stringify(conclusionArray),//诊断结论
        'infoIds': JSON.stringify(infoIds),//特病选项
        'specialId': 1, // 暂时只有腺样体
        'checkResult': Math.round(DocData.checkResult/DocData.totalSpecialScore*100),
        'realResult': parseInt(DocData.realResult),
        'error': parseInt(DocData.error)
    }

    if(baseFn.notNull(DocData.bookingInfo.bookingId)){
        _upData.bookingId = DocData.bookingInfo.bookingId
    }
    if(baseFn.notNull(DocData.bookingInfo.treatmentId)){
        _upData.treatmentId = DocData.bookingInfo.treatmentId
    }
    $('#ill_saveBtnBox').attr('rel','off')
    $.ajax({
        url: baseUrl.base+"patient/saveTreatmentInfo",
        type:'post',
        dataType: "json",
        data:_upData,
        success: function (res){
            if(res.code== 0){
                if (DocData.bookingStatus == 4) {
                    baseFn.infoDialog("病历已完善成功，给予推拿师提成奖励！", function () {
                        baseFn.goPath("-1");
                    });
                    return;
                }
                var _txt='病历更新成功！'
                if(baseFn.notNull(res.results)){
                    if(!baseFn.notNull(DocData.bookingInfo.treatmentId)){
                        DocData.bookingInfo.treatmentId = res.results//如果预约单没有病历 添加病历id
                        _txt = '病历保存成功！'
                    }
                    //可以选择服务和商品
                    if(baseFn.notNull(DocData.bookingInfo.bookingId) && baseFn.notNull(DocData.bookingInfo.treatmentId)){
                        DocData.bookingInfo.canSelGoods = true
                    }else{
                        DocData.bookingInfo.canSelGoods = false
                    }
                }
                eidtingCase(false)
                baseFn.infoDialog(_txt)
                treatmentTest(DocData.bookingInfo.bookingType)
            }else{
                $('#ill_saveBtnBox').attr('rel','on')
                baseFn.infoDialog(res.msg);
            }
        }
    });
});

// 选择历史病历弹窗按钮
$('.fast_caseOfIll').on('click','#illList',function(){
    caseDialog=baseFn.dialog({
        title:'历史病历',
        content:$('.caselistwrap'),
        width:'40em',
        height:'55vh',
        ok:false
    })
});

/*宝宝病历*/
// 收起-展开宝宝列表按钮
$('.consumeListContains').on('click','.arrowDown',function(){
    $(this).toggleClass('arrowDown_active');
    if($(this).hasClass('arrowDown_active')){
        $('.patientList').slideUp();
    }else{
        $('.patientList').slideDown();
    }
});

// ---------------- 事件绑定End ---------------------

//小计
function sumLit(){
    // alert("in 小计");
    $('#PayNum span').text('0')
    var _pay=0,_cost=0;
    DocData.serviceIds=[],DocData.userCardServe=[];
    if($('.js_project_wrap[rel=1]').find('.newAddBtn').length != 0){
        $('.js_sumtit').removeClass('hidden')
        $('.js_project_wrap[rel=1]').find('.newAddBtn').each(function(i,n){
            if(!($(n).hasClass('cardoff'))){
                // break;
                _pay += Number($(n).data('cost'));
            }
            _cost += Number($(n).data('cost'));
            DocData.serviceIds.push($(n).attr('rel'))
        })
    }else{
        $('.js_sumtit').addClass('hidden')
    }
    $('#PayNum span').text(_pay)
    $('.js_sumtit').data('cost',_cost)
    DocData.payService = _pay
    sumTotal()
}
//总计
function sumTotal(uses){
    // alert("in 总计");
    DocData.payGoods = 0
    var _pay = Number($('#PayNum span').text()),_cost=$('.js_sumtit').data('cost')
    DocData.goodsIds=[]
    $('.js_project_wrap[rel=2]').find('.newAddBtn').each(function(i,n){
        var _goodspay = $(n).find('.moneyNumberTip').text()
        _pay += Number(_goodspay)
        _cost += Number(_goodspay)
        DocData.goodsIds.push($(n).attr('rel'))
        DocData.payGoods = DocData.payGoods + Number(_goodspay)
    })


    DocData.pay=_pay
    DocData.cost= _cost
    $('.bottomList_home').find('.likeRed').text(DocData.pay)
    if(!uses){
        //优惠券
        couponlist()
    }
}
//couponlist 优惠券使用
function couponlist(){
    var _upData = {
        userId:DocData.userInfo.userId,
        serviceId:DocData.serviceIds.join(','),
        orderCost:DocData.pay,
        subclinicId:DocData.bookingInfo.subclinicId
    }
    $.get(baseUrl.base+baseUrl.user+'selectUserCouponList',_upData,function(res){
        $('.select_choice').find('option').remove()
        $('.select_choice').append('<option value="">不使用优惠券</option>')
        if(res.code == 0){
            var _couponId = ''
            // if(DocData.orderData != '' && baseFn.notNull(DocData.orderData.orderInfo.couponId)){
            if(DocData.couponId != ''){
                _couponId = DocData.couponId
            }
            DocData.couponList = res.results
            for(var i=0;i<res.results.length;i++){
                var _d = res.results[i]
                // if((_d.subclinicIds == DocData.subclinicId || _d.subclinicIds==0) && _d.isUsed == 0){
                if(_d.isUsed == 0){
                    var _opt = '<option value="'+_d.cardId+'" '
                    if(_couponId != '' && _couponId ==_d.cardId){
                        _opt += 'selected'
                        if(_d.cardType == 1 || _d.cardType == 3){
                            DocData.couponMoney= Number(_d.discountCosts)
                        }else if(_d.cardType == 2){
                            var _seviceelm = $('.js_project_wrap[rel=1]').find('.newAddBtn[rel='+_d.serviceId+']')
                            if(_seviceelm && !_seviceelm.hasClass('cardoff')){
                                DocData.couponMoney= Number(_seviceelm.data('cost'))
                                DocData.payService = DocData.payService - DocData.couponMoney
                            }
                        }
                    }
                    _opt += '>'+_d.cardName+'</option>'
                    $('.select_choice').append(_opt)
                }
            }
            $('.bottomList_home').find('.likeRed').text((DocData.pay-DocData.couponMoney)<0?0:(DocData.pay-DocData.couponMoney))
        }else{
            baseFn.infoDialog(res.msg)
        }
    },'json')
}

// 初始化日期
function birthDay(){
    baseFn.dateTimePick('#birthDay')
}
/*用户基本信息头像*/
function changeImg(){
    $('#Js_previewImgNew').trigger('click');
}
//图片上传
function zcuploadImageCover(e){
    baseFn.imgUpload($(e).parents('form').attr('id'),function(res){
        $(e).prev().find('img').attr('src',res.url);
        $("input[name=userImg]").val(res.url);
    })
}

// 特病相关函数
function bindSpecialClick() {
    // 特病开关
    $("#specialCheck").click(function(){
        if ($(this).hasClass('checkBox_checked')) {
            $(".specialBox").hide();
            $(".specialScoreBox").hide();
            $(this).removeClass("checkBox_checked");
        } else {
            $(".specialBox").show();
            $(".specialScoreBox").show();
            $(this).addClass('checkBox_checked');
        }
    });
    // 特病选项开关
    $("input[type=checkbox][watch=special]").click(function () {
        if ($(this).hasClass('checkBox_checked')) {
            $(this).removeClass("checkBox_checked");
            DocData.checkResult -= parseInt($(this).attr("score"));
        } else {
            $(this).addClass('checkBox_checked');
            DocData.checkResult += parseInt($(this).attr("score"));
        }
        $("#checkResultLabel").html(Math.round(DocData.checkResult/DocData.totalSpecialScore*100) + "%");
        var realScore = parseInt($("#realScore").val());
        DocData.realResult = realScore;
        DocData.error = realScore - (Math.round(DocData.checkResult/DocData.totalSpecialScore*100));
        $("#scoreLabel").html(DocData.error + "%")
    })
    // $("#specialCheck").attr("disabled", false);
    // $("input[type=checkbox][watch=special]").attr("disabled", false);
}

function unBindSpecialClick() {
    $("#specialCheck").unbind();
    $("input[type=checkbox][watch=special]").unbind();
    // $("#specialCheck").attr("disabled", true);
    // $("input[type=checkbox][watch=special]").attr("disabled", true);
}

$("#realScore").change(function (i, n) {
    var realScore = parseInt($(this).val());
    if(!/^(0|[1-9][0-9]?|100)(\.[0-9])?$/.test($(this).val())){
        alert("请输入100以内的数字");
        return;
    }
    DocData.realResult = realScore;
    DocData.error = realScore - (Math.round(DocData.checkResult/DocData.totalSpecialScore*100));
    $("#scoreLabel").html(DocData.error + "%")
});

function renderSpecialInfo(res) {
    $(".specialBox").remove();
    var specialHtml = "";
    DocData.totalSpecialScore = 0;
    for (var i = res.length - 1; i >= 0; i--) {
        var specialObj = res[i];
        specialHtml = $('<div class="couponOption specialBox hidden" style="height:30px;line-height:30px;">\
                            <label class="fast_formTipWidth heavy-weight"></label>\
                            <label class="" style="width:45%">'+specialObj.infoName+'</label>\
                            <input type="checkbox" value="'+specialObj.infoId+'" class="checkBox checkall" watch="special" style="margin-top:3px" score="'+specialObj.scroe+'">\
                            </div>');
        $('#specialBoxBefore').after(specialHtml);
        DocData.totalSpecialScore += parseInt(specialObj.scroe);
    }
}
